#! /usr/bin/env python
#
# Implement cookbook using pyfitsio
import sys
import os

import ctypes

# Use just the C-types bindings to CFITSIO
from fitsio import cfitsio, pyfitsio

def main():
    '''
    Read a FITS image and determine the minimum and maximum pixel values
    '''

    filename = 'atestfil.fit'
    
    ff = pyfitsio.open(filename)

    # Read NAXIS1 and NAXIS2 keywords to get image size. Expecting a 
    # 2 dimensional image here
    naxis1, naxis2 = ff.read_axes()
    print naxis1, naxis2

    # Read the image 1000 bytes at a time
    buffsize = 1000
    buffer = (ctypes.c_float * buffsize)()

    npixels = naxis1 * naxis2
    fpixel  = ctypes.c_longlong(1)
    nullval = ctypes.c_float(0)
    datamin = 1.0e30
    datamax = -1.0e30
    anynull = ctypes.c_int()

    status = ctypes.c_int(0)
    
    while (npixels > 0):

        # read as many pixels as will fit in the buffer
        nbuffer = ctypes.c_longlong(npixels)
        if npixels > buffsize:
            nbuffer = ctypes.c_longlong(buffsize)

        cfitsio.fits_read_img(ff.fptr, cfitsio.TFLOAT, fpixel, nbuffer, \
                                  ctypes.byref(nullval), buffer, \
                                  ctypes.byref(anynull), ctypes.byref(status))
        pyfitsio.check_error(status)

        for ii in range(nbuffer.value):
            if buffer[ii] < datamin:
                datamin = buffer[ii]
            if buffer[ii] > datamax:
                datamax = buffer[ii]

        npixels -= nbuffer.value
        fpixel.value += nbuffer.value

    print "\nMin and max image pixels =", datamin, datamax

    ff.close()

if __name__ == '__main__':
    main()
